/**
 * 
 */
package net.sf.cldsql.dj.container;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.cldsql.dj.container.base.DiSetup;
import net.sf.cldsql.dj.utl.DiException;

/**
 * ContainerServletUtl
 */
public class DiServletUtl {
    /**
     * 
     */
    public static final String DI_CONTAINER_CONF = "SjContainerConf";
    public static final String DICONTAINER_ID = "__sjcontainer_id__";
    
    final Logger log = LoggerFactory.getLogger(DiServletUtl.class);
    
    public static DiContainer get(ServletContext ctx) {
        return (DiContainer)ctx.getAttribute(DICONTAINER_ID);
    }
    
    public static void init(ServletContext ctx) {
        try {
            String setupClassName = ctx.getInitParameter("SjSetupClass");
            Class setupClass = Class.forName(setupClassName);
            DiSetup setup = (DiSetup)setupClass.newInstance();
            init(ctx, setup);
        } catch (ClassNotFoundException e) {
            throw new DiException(e);
        } catch (InstantiationException e) {
            throw new DiException(e);
        } catch (IllegalAccessException e) {
            throw new DiException(e);
        }
        
        
    }
    
    public static void init(ServletContext ctx, DiSetup setup) {
        final Logger log = LoggerFactory.getLogger(DiServletUtl.class);
        
        if (ctx.getAttribute(DICONTAINER_ID) == null) {
            log.debug("load conf:" + ctx.getInitParameter(DI_CONTAINER_CONF));
            ctx.setAttribute(DICONTAINER_ID, setup.build(ctx.getRealPath("/") + ctx.getInitParameter(DI_CONTAINER_CONF)));
        } else {
            log.debug("init called again.");
        }
    }
}
